package com.huluobo.a2204kotlinjetpackdemo.paging

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.huluobo.a2204kotlinjetpackdemo.R
import com.huluobo.a2204kotlinjetpackdemo.databinding.ItemPagingBinding

/**
 *  Created by LC on 2024/8/19.
 */
class PagingAdapter : PagingDataAdapter<GitPagingBean, PagingAdapter.ViewHolder>(diffUtilCallBack) {
    companion object {
        //item内容对比工具
        //新加入的item会先经过对比工具对比是否一致
        //areItemsTheSame 对比id来判断2个item是否是一个,如果是一个就不会添加
        //areContentsTheSame 对比内容是否一致,会走在areItemsTheSame的后面,如果id相同,再对比内容,都相同就不添加
        private val diffUtilCallBack = object : DiffUtil.ItemCallback<GitPagingBean>() {
            override fun areItemsTheSame(oldItem: GitPagingBean, newItem: GitPagingBean): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: GitPagingBean, newItem: GitPagingBean): Boolean {
                return oldItem == newItem
            }
        }
    }


    //给viewHolder传递数据用的
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        //把单独的bean传递给xml
        holder.binding?.bean = getItem(position)
    }

    //给viewHolder绑定布局用的
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_paging, parent, false)
        return ViewHolder(view)
    }

    //视图保持器,所有的adapter都需要有一个viewHolder
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val binding: ItemPagingBinding? = DataBindingUtil.bind(itemView)
    }
}